<template>
    <div class="QrcodeLogin">
        <div class="qrcode-wxgzh" v-if="wxGzhQrcodeShow">
            <img class="login-wxgzh" :src="loginImg"/>
            <div v-if="invalidQrCode" class="code-invalid">
                {{ qrTitle }}，
                <span style="color: #067BEF;cursor: pointer;" @click="getAuthUrl()">刷新</span>
            </div>
        </div>
        <img v-else-if="isLoginError" class="login-img" :src="loginImg"/>
        <img v-else class="QrcodeLogin-loading" src="@/views/login/img/failed.png"/>
        <div :class="[isLoginError?'QrcodeLogin-text-true':'QrcodeLogin-text']">{{titleVal}}</div>
    </div>
</template>

<script>
import LoginApi from "@/common/api/login.js";
import userUser from "../../stores/userUser";
import useMain from "../../stores/useMain";
import { mapActions } from 'pinia'
import {TokenUtil} from "@lowcode/jpaas-base-lib";
import loginUrl from "@/views/login/img/loading.gif";

const ROOT_TENANT = "1"
export default {
    name: "QrcodeLogin",
    data(){
        return {
            appType: null,
            tenantId: null,
            redirectUrl: "",
            code: null,
            loginType:'',
            isLoginError: true,
            qrTitle:this.i18n('tips.qrInvalid',"二维码已过期"),
            titleVal:this.i18n('tips.getQrcode','正在获取二维码，请稍候...'),
            hostName:"",
            loginImg:loginUrl,
            wxGzh:{},
            intervalFun:"",
            wxGzhQrcodeShow:false,
            invalidQrCode:false
        }
    },
    created(){
        this.setLogined(false);
        this.loginType = this.$route.query.loginType;
        if(!this.loginType ){
            this.loginType  = localStorage.getItem("LOGIN_TYPE")?localStorage.getItem("LOGIN_TYPE"):1;
        }else{
            localStorage.setItem("LOGIN_TYPE",this.loginType)
        }
        this.setLoginUrl();
        this.tenantId = this.$route.query.tenantId;
        if (!this.tenantId || this.tenantId.trim().length == 0) {
            this.tenantId = ROOT_TENANT;
        }
        this.hostName = this.$route.query.hostName;
        this.code = this.$route.query.code;
        //扫码回调
        if (this.code) {
            this.titleVal=this.i18n('tips.loging','正在进行登录，请稍候...');
            this.autoLoginByCode();
            return;
        }
        this.getAuthUrl();
    },
    computed: {},
    methods: {
        ...mapActions(userUser,['AutoLoginByCode','setToken']),
        ...mapActions(useMain,['setLogined']),
        i18n(name, text, key) {
            return this.$ti18(name, text, "viewsUser", key);
        },
        //手机验证码登录
        mobileCodeLogin(ticketJson) {
            ticketJson.hostName = this.hostName;
            if(ticketJson.hostName == 'localhost'){
                ticketJson.hostName="";
            }
            ticketJson.tenantId = this.tenantId;
            this.$router.push({name: 'mobileCodeLogin', query: ticketJson});
        },
        getAuthUrl() {
            this.qrTitle=this.i18n('tips.qrInvalid',"二维码已过期");
            if("1"==this.loginType){
                this.wxGzh={};
                this.invalidQrCode=false;
            }
            let params = {
                tenantId: this.tenantId,
                redirectUrl: this.redirectUrl,
                loginType:this.loginType,
                state:'',
                paramType:"pc"
            };
            let self_ = this;
            LoginApi.getAuthUrl(params).then(res => {
                if (!res.success || !res.data) {
                    let message=self_.i18n('tips.qrCode','获取二维码失败');
                    self_.isLoginError=false;
                    self_.titleVal=message;
                    self_.errorMsg(message, res.message);
                    return;
                }
                if("1"==self_.loginType){
                    self_.setWxGzh(res.data);
                    return;
                }
                //跳转到二维码页面
                window.location.href = res.data;
            }).catch(err => {
                let message=self_.i18n('tips.qrCode','获取二维码失败');
                self_.isLoginError=false;
                self_.titleVal=message;
                self_.errorMsg(message, JSON.stringify(err));
            })
        },
        setIntervalFun(){
            let start = Date.now();
            let self =this;
            this.intervalFun = setInterval(() => {
                // 计算已过去的时间
                let elapsed = Date.now() - start;
                let num = elapsed / 1000;
                console.debug("执行定时器时间。。。。。num="+num+"---总时间："+this.wxGzh.expire_seconds);
                if (num >= this.wxGzh.expire_seconds) {
                    console.debug("停止执行定时器。。。。。");
                    self.invalidQrCode=true;
                    // 清除定时器
                    clearInterval(self.intervalFun);
                }
                // 每秒执行的操作
                this.getTokenByTicket()
            }, 1000);
        },
        setWxGzh(wxGzh){
            this.wxGzh=wxGzh;
            let showqrcodeUrl = this.wxGzh.showqrcodeUrl+"?ticket="+this.wxGzh.ticket;
            this.loginImg = showqrcodeUrl;
            this.titleVal=this.i18n('tips.scanWxGzhLogin',"微信扫码关注公众号完成登录");
            this.wxGzhQrcodeShow=true;
            this.setIntervalFun();
        },
        getTokenByTicket() {
            let params = {
                tenantId: this.tenantId,
                ticket: this.wxGzh.ticket,
                sceneId:this.wxGzh.sceneId,
                hostName:this.hostName
            };
            var self_ = this;
            LoginApi.getTokenByTicket(params).then(res => {
                console.debug("轮询微信公众是否扫码--结果。。。。。res="+JSON.stringify(res));
                if(res.isWxGzhNewUser || res.isWxGzhNewUser==true || res.isWxGzhNewUser=="true"){
                    // 清除定时器
                    clearInterval(self_.intervalFun);
                    self_.mobileCodeLogin(res);
                    //跳转到绑定手机验证码登录
                    return;
                }

                let token = res.access_token;
                if(token){
                    // 清除定时器
                    clearInterval(self_.intervalFun);
                    TokenUtil.setToken(token);
                    self_.setToken(token);
                    self_.$router.push({name: 'appHome'}, () => {
                    });
                }
                if(res.loginSuccess=="LOGIN_FAIL"){
                    self_.qrTitle =self_.i18n('tips.failureLogin',"登录失败");
                    self_.invalidQrCode = true;
                    self_.errorMsg(this.i18n('tips.warningTitle',"警告信息"), res.failMessage);
                    // 清除定时器
                    clearInterval(self_.intervalFun);
                }
            })
        },
        //根据code信息尝试自动登录
        autoLoginByCode() {
            //根据Code获取钉钉用户ID
            let params = {
                tenantId: this.tenantId,
                code: this.code,
                loginType:this.loginType
            };
            var self_ = this;
            //用钉钉用户登录系统
            this.AutoLoginByCode(params,function (res,err){
                if(!err){
                    self_.loginSuccess(res);
                }else {
                    let message=self_.i18n('tips.failure','自动登录失败');
                    self_.isLoginError=false;
                    self_.titleVal=message;
                    self_.errorMsg(message, JSON.stringify(err));
                }
            })
        },
        loginSuccess(res) {
            if (!res.success) {
                let message=this.i18n('tips.failureLogin','登录失败')+":"+this.i18n('tips.application','请先在手机端应用中绑定！');
                this.isLoginError=false;
                this.titleVal=message;
                this.errorMsg(message);
                return;
            }
            this.$router.push({name: 'appHome'}, () => {
            });
        },
        errorMsg(title, msg) {
            //出错时消息提醒
            this.$notification.error({
                message: title,
                description: msg
            });
            var router = this.$router;
            const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
            wait(5000).then(() => router.push({
                name: 'login'
            }));
        },
        setLoginUrl(){
            let path = this.$route.path;
            let loginUrl = location.href.split(path)[0] +"/qrcodeLogin";
            if(this.tenantId){
                loginUrl += "?tenantId=" + this.tenantId;
            }
            this.redirectUrl =  loginUrl;
        }
    }
}
</script>

<style scoped>
.QrcodeLogin{
    display: flex;
    flex-direction: column;
    background: white;
    position: fixed;
    top: 0;
    left: 0px;
    bottom: 0px;
    right: 0px;
    z-index: 9999;
    transform: inherit;
    justify-content: center;
    align-items: center;
}
.login-img{
    width: 700px;
    margin-top: -200px;
}
.QrcodeLogin-loading{
    width: 400px;
    margin-top: -200px;
}
.qrcode-wxgzh{
    width: 200px;
    height: 200px;
    background: #fff;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #e9edf2;
    margin: 0 auto 30px;
    position: relative;
    overflow: hidden;
}
.login-wxgzh{
    width: 100%;
    height: 100%;
}
.code-invalid{
    width: 200px;
    height: 200px;
    line-height: 200px;
    background: rgba(255, 255, 255, 0.95);
    position: absolute;
    text-align: center;
    top: 0;
    left: 0;
}
</style>
